import { reactive, ref,Ref } from "vue";
import type { FormInstance } from "element-plus";
import { ajax } from "./request";
import { ElMessageBox } from "element-plus";

import {IStringKey,IListResult} from "@my/types";

/**
 * 
 * @param model 模块名称
 * @param pk 主键字段的名称（删除时需要），默认为：t_模块名_pk
 * @param listURL 查询列表的URL地址，默认为：/模块名/queryList
 * @param deleteURL 删除数据的URL地址，默认为：/模块名/delete
 * @returns 
 */
export default function listSetup(model: string, 
    pk: string = `t_${model}_pk`,
    listURL:string = `/${model}/queryList`,
    deleteURL:string = `/${model}/delete`):IListResult {
    let myForm = ref<FormInstance>();

    let row = ref();

    let count = ref(0);

    let showObject = reactive<IStringKey<boolean>>({
        insert: false,
        update: false,
    });

    let useObject = reactive<IStringKey<boolean>>({
        insert: false,
        update: false,
    });

    const formData = reactive({
        page: 1,
        rows: 10,
    });

    const tableData = reactive<Array<IStringKey>>([]);

    function handleQuery(page: number):void {
        if (page) {
            formData.page = page;
        }
        ajax(listURL, formData).then((res) => {
            if (res.data.status > 0) {
                // 先删除tableData中的所有数据
                tableData.length = 0;
                // 把新的数据追加进去
                tableData.push(...res.data.result_data);
                count.value = res.data.count;
            }
        });
    }

    /**
     * 重置表单，并重新查询数据
     */
    function handleReset(myForm: any):void {
        if (myForm) {
            myForm.resetFields();
        }
        formData.rows = 10;
        handleQuery(1);
    }

    // handleReset(null);


    /**
     * show: show.update = true | show.insert = true
     */
    function handleShow(show: IStringKey<boolean>, data: IStringKey | null):void {
        // 遍历对象的有key
        for (let key in showObject) {
            // 如果当前key在show中有值（true），那么showObject.key = true，否则false
            if (show[key]) {
                useObject[key] = true;
                showObject[key] = true;
            } else {
                showObject[key] = false;
            }
        }
        if (data) {
            row.value = data;
        }
    }

    function handleClose(updated: boolean):void {
        for (let key in showObject) {
            showObject[key] = false;
        }
        if (updated) {
            handleReset(myForm.value);
        }
    }

    /**
     * 改变每页行数
     */
    function handleSizeChange(v: number):void {
        formData.rows = v;
        handleQuery(1);
    }

    /**
     * 改变当前页数
     */
    function handleCurrentChange(v: number):void {
        handleQuery(v);
    }

    /**
     * 删除数据
     */
    function handleDelete(row: IStringKey):void {
        ElMessageBox.confirm("确认删除该选项吗，删除后将不可恢复?", "删除确认", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
        }).then(() => {
            let deleteData:IStringKey = {};
            deleteData[pk] = row[pk];
            ajax(deleteURL, deleteData).then((res) => {
                if (res.data.status > 0) {
                    alert("删除成功");
                    // 方式一：重新查询列表
                    // handleReset(myForm);
                    // 方式二：重表格中把数据删除
                    tableData.splice(tableData.findIndex(v => v[pk] = row[pk]), 1);
                }
            })
        });
    }

    return {
        myForm,
        formData,
        count,
        showObject,
        useObject,
        tableData,
        row,
        handleReset,
        handleShow,
        handleQuery,
        handleClose,
        handleDelete,
        handleCurrentChange,
        handleSizeChange
    }
}